<?php
$serv = new swoole_server('0.0.0.0', 9510);
$serv->set(array(
    'daemonize' => 1,
    'worker_num' => 8, //worker进程数量
    'task_worker_num' => 50, //task进程数量 即为维持的MySQL连接的数量
    'log_file' => '/var/www/swoole/cli/log/9510.log',
    'max_request' =>  10000, // 单个worker 最大处理数
    "open_eof_check"=> 1,
    "package_eof"=>"\r\n\r\n",
    "dispatch_mode" => 3  // 1平均分配 2固定taskid 3 抢占
));

function my_onReceive($serv, $fd, $from_id, $data)
{
    //互不影响
      $serv->task($data);
//    $serv->after(1000, function() use ($serv, $fd,$data) {
//        $serv->task($data);
//    });

//    $serv->after(2000, function() use ($serv, $fd,$data) {
//        $serv->task($data);
//    });
//
//    $serv->after(3000, function() use ($serv, $fd,$data) {
//        $serv->task($data);
//    });
}

function my_onTask($serv, $task_id, $from_id, $sql)
{
    //sql  查询
    $sqlData = explode("\r\n\r\n",$sql);
    $client = new swoole_client(SWOOLE_SOCK_TCP);//创建swoole tcp客户端
    $client->connect('127.0.0.1', 9509, 10) or die("连接失败");//连接server
    foreach($sqlData as $k=>$v){
        if(!$v){
            continue;
        }
        $client->send($v);
        $data = @$client->recv();//阻塞接受返回的结果
        file_put_contents("/var/www/swoole/cli/log/task.txt",json_encode($data)."--|\r\n",FILE_APPEND);
    }
    $client->close();
    $serv->finish("OK:");

}

function my_onFinish($serv, $task_id, $data)
{
    echo "任务完成";//taskwait 没有触发这个函数。。
    echo "AsyncTask Finish:Connect.PID=" . posix_getpid() . PHP_EOL;
}

$serv->on('receive', 'my_onReceive');
$serv->on('task', 'my_onTask');
$serv->on('Finish', 'my_onFinish');

$serv->start();//启动server
